﻿
using B.S.BsicData.Writer.Api.Application.Command.RoleMenu;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using MediatR;

namespace B.S.DataBase.MyWrite.Api.Application.Command.RoleMenu 
{
    public class CreateRoleMenuCommandHandler : IRequestHandler<CreateRoleMenuCommand, APIResult<object>>
    {
        private readonly IBaseRepository<RoleMenuModel> rmRepository;

        public CreateRoleMenuCommandHandler(IBaseRepository<RoleMenuModel> rmRepository)
        {
            this.rmRepository = rmRepository;
        }

        public Task<APIResult<object>> Handle(CreateRoleMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            // 将 UserId 列表转换为 UserRole 对象列表（RoleId 固定为 1）
            var userRoles = request.MenuId  
                .Select(p => new RoleMenuModel { MenuId = p, RoleId = request.RoleId })
                .ToList();

            // 批量添加并保存
            var res = rmRepository.AddRanges(userRoles).Result;
            result.Code = APIEnum.添加成功;
            result.Msg = "批量添加成功";
            result.data = res;

            return Task.FromResult(result);
        }
    }
}
